﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace LiveProjectManager.DDD.Services
{
    public class FileService: Base.Service<Domains.File>
    {
        public FileService() : base()
        {
        }


        override public ICollection<Domains.File> getAll(int paginateBy = 0, int page = 1)
        {
            if (paginateBy > 0)
            {
                if (page <= 0)
                    page = 1;
                return (from f in _repository orderby f.Id select f).Skip(paginateBy * (page - 1)).Take(paginateBy).ToList();
            }
            return (from f in _repository orderby f.Id select f).ToList();
        }


        override public Domains.File getById(long myId)
        {
            ICollection<Domains.File> myResults = (from f in _repository where f.Id == myId select f).ToList();
            return (myResults.Count != 1) ? null : myResults.First();
        }


        public Domains.File getByPath(string myPath)
        {
            ICollection<Domains.File> myResults = (from f in _repository where f.Path == myPath select f).ToList();
            return (myResults.Count != 1) ? null : myResults.First();
        }


        public bool exists(string myPath)
        {
            return getByPath(myPath) != null;
        }


        override public bool remove(long myId, bool autoSave = true)
        {
            Domains.File myFile = getById(myId);
            if (myFile == null)
                return false;
            _repository.Remove(myFile);
            if (autoSave)
                _context.SaveChanges();
            return true;
        }


        public bool create(
            string myPath,
            long mySize,
            bool autoSave = true
        )
        {
            try
            {
                if (exists(myPath))
                    return false;
                DDD.Domains.File myFile = new DDD.Domains.File
                {
                    Path = myPath,
                    Size = mySize,
                    CreatedOn = DateTime.Now
                };
                _repository.Add(myFile);
                if (autoSave)
                    _context.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}